<template>
  <section>
    <!--工具条 高级查询和新增-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" >
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表 分页数据展示-->
    <el-table :data="employees" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="username" label="员工名称" width="80">
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="100"  sortable>
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="120"  sortable>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="100"  sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="80" sortable>
        <template scope="scope">
          <span style="color: #11b95c" v-if="scope.row.state==1">启用</span>
          <span style="color: red" v-else>禁用</span>
        </template>
      </el-table-column>
      <el-table-column prop="department.name" label="部门名称" width="80" sortable>
      </el-table-column>
      <el-table-column prop="role_name" label="所属角色" width="100"  sortable>
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleSave(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条  批量删除和分页栏-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :current-page="currentPage"
                     :page-size="pageSize" :total="totals" style="float:right;">
      </el-pagination>
    </el-col>

    <!--添加和修改界面对话框-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <!-- prop="name" 需要验证就加上这个属性，不需要验证就不加 -->
        <el-form-item label="员工姓名" prop="username">
          <el-input v-model="saveForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工电话" prop="phone">
          <el-input v-model="saveForm.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="saveForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" >
          <el-input v-model="saveForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="saveForm.age" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
<!--        <el-form-item label="部门" prop="department.name">-->
<!--          <template>-->
<!--            <el-select v-model="saveForm.manager_id" placeholder="请选择">-->
<!--              <el-option-->
<!--                  v-for="item in managers"-->
<!--                  :label="item.username"-->
<!--                  :value="item.id">-->
<!--                <span style="float: left">{{ item.username }}</span>-->
<!--                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>-->
<!--              </el-option>-->
<!--            </el-select>-->
<!--          </template>-->
<!--        </el-form-item>-->
        <el-form-item label="所属部门">
          <el-cascader v-model="saveForm.department_id"
            :options="deptTree"
            :props="{
              checkStrictly: true,
              label:'name', //回显哪个数据
              value:'id'   //回显时需要，传值时也需要
            }"
            clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="所属角色">
        <el-select v-model="saveForm.role_id" placeholder="请选择">
          <el-option
              v-for="item in roles"
              :label="item.name"
              :value="item.id">
            <span style="float: left">{{ item.name }}</span>
          </el-option>
        </el-select>
        </el-form-item>
      </el-form>
      <!--
        @click.native="saveSubmit" - 点击提交的时候调用saveSubmit方法
        :loading="saveLoading" - 提交的加载加载框
      -->
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>


export default {
  data() {
    return {
      //1.分页相关的模型数据
      employees: [], //绑定到表格 - 显示列表数据 - 请求完成之后
      totals: 0,  //总数量 - 计算分页栏 - 请求完成后
      currentPage: 1, //当前页 - 分页栏默认当前页显示
      pageSize: 5, //每页显示的条数 - 计算分页栏
      listLoading: false, //表格上的加载框

      //高级查询数据模型
      keyword: '',
      // filters:[],
      //批量删除的数据模型
      sels: [],//列表选中列

      //添加和修改的相关模型数据
      title: '',
      saveFormVisible: false, //控制对话框是否显示 -默认不显示
      saveLoading: false, //加载框
      saveFormRules: {
        //表单项中的prop属性
        username: [
          {required: true, message: '请输入员工姓名', trigger: 'blur'}
        ],
        phone: [
          {required: true, message: '请输入员工电话', trigger: 'blur'}
        ]
      },

      //编辑界面数据
      saveForm: {
        id: null,
        username: '',
        phone: '',
        age:null,
        password:'',
        email:'',
        state: 1,
        department_id: null,
        role_id:null,
        role_name:""
      },
      //下拉框数据模型：
      managers:[],

      //获取所有角色
      roles:[],
      //级联框数据模型
      deptTree:[],
    }
  },
  methods: {
    //1.分页查询：获取部门分页数据【增删改,页面记载都要去调用】
    getEmployees() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword
      };
      this.listLoading = true;
      this.$http.post("/employee", para).then(res => {
        //给totals赋值 - 计算分页栏
        this.totals = res.data.totals;
        //赋值分页数据 - 显示当前页的分页数据
        this.employees = res.data.data;
        //隐藏加载框
        this.listLoading = false;

      }).catch(res => {
        this.$message.error('系统繁忙，请稍后再试！！！')
      })
    },
    //点击分页数字键跳页显示新数据
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getEmployees();
    },

    //2高级查询方法
    keywordQuery() {
      this.currentPage = 1;
      this.getEmployees();
    },

    //3.删除的方法
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => { //确认框点击确定走then
        console.log(row);
        this.listLoading = true;

        this.$http.delete("/employee/" + row.id).then(res => {
          //删除成功
          this.listLoading = false;
          //判断后端传回给前端的AjaxResult返回值中success的值，
          // 为true就是删除成功，false就是删除失败
          if (res.data.success) {
            this.$message.success("删除成功");
            //删除优化：计算总页数 = 向上取整 总条数/每页条数
            var totalPage = Math.ceil(this.totals / this.pageSize);
            //删除最后一页的最后一个数据，而且不能是第一页的时候，让当前页=当前页-1
            if (this.currentPage == totalPage && (this.totals - 1) % this.pageSize == 0 && this.currentPage != 1) {
              this.currentPage = this.currentPage - 1;
            }

            this.getEmployees();//删除了之后在这里才会更新总数量totals,之前是没有更新到的
          } else {
            this.$message.error("删除失败，系统异常，请稍后重试")
          }
        }).catch(res => {
          this.$message.error("系统异常，请稍后重试")
        })
      }).catch(() => {
      });
    },


    //4.批量删除 选项改变的时候就会触发
    selsChange: function (sels) {
      //选中的对象 - 数组
      this.sels = sels;
    },
    //批量删除的逻辑
    //批量删除
    batchRemove: function () {
      //获取数组中的每一个对象的id，-数组
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;

        this.$http.patch("/employee", ids).then(res => {
          this.listLoading = false;
          if (res.data.success) {
            this.$message.success = ("删除成功");
            this.currentPage = 1;
            this.getEmployees();
          } else {
            this.$message.error("系统异常，请稍后重试【500】");
          }
        }).catch(res => {
          this.$message.error("系统异常，请稍后重试【服务器没开，404,400】")
        })
      }).catch(() => {
      });
    },

    //5,点击修改按钮弹出对话框界面
    handleSave: function (index, row) {

      this.title = '修改';
      // this.getManagers();
      this.getRoles();
      //获取部门树
      this.getDeptTree();
      this.saveFormVisible = true;
      this.saveForm = Object.assign({}, row);
    },
    //点击添加弹出对话框
    handleAdd: function () {

      this.title = "添加";
      //获取所有经理
      // this.getManagers();
      this.getRoles();

      //获取部门树
      this.getDeptTree();
      this.saveFormVisible = true;
      this.saveForm = {
        id: null,
        username: '',
        phone: '',
        age:null,
        password:'',
        email:'',
        state: 1,
        department_id: null,
        role_id:null,
        role_name:""
      };
    },
    //点击提交数据
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.saveForm);
            //对上级部门提交处理 [],[1,2],[1],1
            let result = para.department_id;
            //如果为null和[],就直接赋值null
            if(result==null||result.length==0){
              para.department_id = null;
              //如果有值result.length为undefined，判断为false
            }else if (result.length){
              //取最后一个数
              para.department_id = result[result.length-1]
            }



            this.$http.put("/employee",para).then(res=>{
              //关闭提交的加载框
              this.saveLoading = false;
              //关闭对话框
              this.saveFormVisible = false;
              if(res.data.success){
                this.$message.success("操作成功");
                this.getEmployees();
              }else{
                this.$message.error("系统异常，请稍后重试!【500】");
              }
            }).catch(res=>{
              this.$message.error("系统异常，请稍后重试!【服务器没开,404,400,405】")
            })
          });
        }
      });
    },

    // //获取所有经理对象
    // getManagers(){
    //   this.$http.get("/employee").then(res=>{
    //     //获取后端传的集合//赋值给manager，再再表格里循环显示
    //     this.managers = res.data;
    //   })
    // },

    //获取部门树
    getDeptTree(){
      this.$http.get("/department/deptTree").then(res=>{
        this.deptTree = res.data;
      })
    },
    //获取所有角色
    getRoles(){
      this.$http.get("/role").then(res=>{
        this.roles = res.data;
      })
    }
  },
  mounted() {
    this.getEmployees();
  }
}


</script>

<style scoped>

</style>